import axios from "axios";
import { getStore, setStore } from "./storage.js";
import { router } from "../router/index";
import { Message } from "view-design";
import Cookies from "js-cookie";
import { handleRefreshToken } from "../api/index";
import { v4 as uuidv4 } from 'uuid';
import env from '@/env'
// import {BASE} from '@/utils/serviceUtil.js'
// console.log('env', env);
const replaceUrl = (url) => {
  let apiUrl = env.apiUrl + url
  return apiUrl
}
// 统一请求路径前缀
export const commonUrl = replaceUrl(BASE.API.common)
export const managerUrl = replaceUrl(BASE.API.manager) + BASE.PREFIX
// 文件上传接口
export const uploadFile = commonUrl + "/common/common/upload/file";
console.log('uploadFile', uploadFile)

const service = axios.create({
  timeout: 8000,
  baseURL: managerUrl
});
var isRefreshToken = 0;
const refreshToken = getTokenDebounce();
service.interceptors.request.use(
  config => {
    let urlArr = config.url.split('?')
    if (urlArr[1]) {
      let paramStr = `?${urlArr[1]}`.replace(/([?&])([^=]+)=(null|undefined)/g, '')
      if (paramStr) {
        config.url = `${urlArr[0]}?${paramStr}`
      } else {
        config.url = `${urlArr[0]}`
      }
    }
    if (config.params) {
      if (Array.isArray(config.params)) {

      } else {
        let submitParam = {}
        for (let key in config.params) {
          if (config.params[key] !== undefined && config.params[key] !== null && config.params[key] !== "null") {
            submitParam[key] = config.params[key]
          }
        }
        config.params = submitParam
      }
    }
    if (config.data) {
      if (config.data instanceof FormData) {
        let submitParam = new FormData();
        for (let key of config.data.keys()) {
          let value = config.data.get(key)
          if (value !== undefined && value !== null && value !== "null") {
            submitParam.append(key, value);
          }
        }
        config.data = submitParam
      } else if (Array.isArray(config.data)) {} else {
        let submitParam = {}
        for (let key in config.data) {
          if (config.data[key] !== undefined && config.data[key] !== null && config.data[key] !== "null") {
            submitParam[key] = config.data[key]
          }
        }
        config.data = submitParam
      }
    }
    if (config.method == "get") {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      };
    }
    if (config.url.indexOf('/api/') === 0) {
      config.baseURL = ''
    } else {
      config.baseURL = managerUrl
    }

    let uuid = getStore("uuid");
    if (!uuid) {
      uuid = uuidv4();
      setStore('uuid', uuid);
    }
    config.headers["uuid"] = uuid;
    return config;
  },
  err => {
    Message.error("请求超时");
    return Promise.reject(err);
  }
);

// http response 拦截器
service.interceptors.response.use(
  response => {
    const data = response.data;
    // 根据返回的code值来做不同的处理(和后端约定)
    if (!data.success && data.message) {
      Message.error(data.message);
    }
    console.log('响应结果:', data)
    switch (data.code) {
      case 400:
        if (data.message !== null) {
          Message.error(data.message);
        } else {
          Message.error("系统异常");
        }
        break;
      case 20004:
      case 401:
      case 403:
        // 未登录 清除已登录状态
        Cookies.set("userInfoManager", "");
        setStore("accessToken", "");
        console.log('response:成功里面的code')
        if (router.history.current.name != "login") {
          if (data.message !== null) {
            Message.error(data.message);
          } else {
            Message.error("未知错误，请重新登录");
          }
          router.push("/login");
        }
        return data;
        break;
      case 500:
        // 系统异常
        if (data.message !== null) {
          Message.error(data.message);
        } else {
          Message.error("系统异常");
        }
        break;
      default:
        return data;
    }
  },
  async error => {
    // 返回状态码不为200时候的错误处理
    if (error.response) {
      if (error.response.status === 401) {
        // 这种情况一般调到登录页
      } else if (error.response.status === 404) {
        // 避免刷新token报错
      } else if (error.response.status === 403 || error.response.data.code === 20004) {
        console.log('error响应结果:', error.response)
        Cookies.set("userInfoManager", "");
        router.push("/login");
        // isRefreshToken++;
        // if (isRefreshToken === 1) {
        //   const getTokenRes = await refreshToken();
        //   if (getTokenRes === "success") {
        //     console.log('refresh---成功')
        //     // 刷新token
        //     if (isRefreshToken === 1) {
        //       error.response.config.headers.accessToken = getStore(
        //         "accessToken"
        //       );
        //       return service(error.response.config);
        //     } else {
        //       router.go(0);
        //     }
        //   } else {
        //     console.log('refresh---失败')
        //     Cookies.set("userInfoManager", "");
        //     router.push("/login");
        //   }
        //   isRefreshToken = 0;
        // }
      } else {
        // 其他错误处理
        Message.error(error.response.data.message);
      }
    }
    /* router.push("/login") */
    return Promise.resolve(error);
  }
);

// 防抖闭包来一波
function getTokenDebounce() {
  let lock = false;
  let success = false;
  return function() {
    if (!lock) {
      lock = true;
      let oldRefreshToken = getStore("refreshToken");
      handleRefreshToken(oldRefreshToken)
        .then(res => {
          if (res.success) {
            let { accessToken, refreshToken } = res.result;
            setStore("accessToken", accessToken);
            setStore("refreshToken", refreshToken);

            success = true;
            lock = false;
          } else {
            success = false;
            lock = false;
            router.push("/login");
          }
        })
        .catch(err => {
          success = false;
          lock = false;
        });
    }
    return new Promise(resolve => {
      // 一直看lock,直到请求失败或者成功
      const timer = setInterval(() => {
        if (!lock) {
          clearInterval(timer);
          if (success) {
            resolve("success");
          } else {
            resolve("fail");
          }
        }
      }, 500); // 轮询时间间隔
    });
  };
}

export const getRequest = (url, params, resBlob) => {
  let accessToken = getStore("accessToken");
  let data = {
    method: "get",
    url: `${url}`,
    params: params,
    headers: {
      accessToken: accessToken
    },
    responseType: "blob"
  };
  if (resBlob != "blob") {
    delete data.responseType;
  }
  return service(data);
};


export const postRequest = (url, params, headers) => {
  let accessToken = getStore("accessToken");
  return service({
    method: "post",
    url: `${url}`,
    data: params,
    transformRequest: headers ?
      undefined : [
        function(data) {
          let ret = "";
          for (let it in data) {
            ret +=
              encodeURIComponent(it) +
              "=" +
              encodeURIComponent(data[it]) +
              "&";
          }
          ret = ret.substring(0, ret.length - 1);
          return ret;
        }
      ],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      accessToken: accessToken,
      ...headers
    }
  });
};

/** 不带form表单不带transformRequest */
export const postRequestWithNoForm = (url, params) => {
  let accessToken = getStore("accessToken");
  return service({
    method: "post",
    url: `${url}`,
    data: params,

    headers: {
      accessToken: accessToken
    }
  });
};

// export const postRequestWithHeaders = (url, params) => {
//   let accessToken = getStore("accessToken");
//   return axios({
//     method: "post",
//     url: `${url}`,
//     data: params,

//     headers: {
//       accessToken: accessToken,
//       "Content-Type": "application/x-www-form-urlencoded"
//     }
//   });
// };

export const putRequest = (url, params, headers) => {
  let accessToken = getStore("accessToken");
  return service({
    method: "put",
    url: `${url}`,
    data: params,
    transformRequest: headers ?
      undefined : [
        function(data) {
          let ret = "";
          for (let it in data) {
            ret +=
              encodeURIComponent(it) +
              "=" +
              encodeURIComponent(data[it]) +
              "&";
          }
          ret = ret.substring(0, ret.length - 1);
          return ret;
        }
      ],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      accessToken: accessToken,
      ...headers
    }
  });
};

export const putRequestWithNoForm = (url, params) => {
  let accessToken = getStore("accessToken");
  return service({
    method: "put",
    url: `${url}`,
    data: params,

    headers: {
      accessToken: accessToken
    }
  });
};

export const deleteRequest = (url, params) => {
  let accessToken = getStore("accessToken");
  return service({
    method: "delete",
    url: `${url}`,
    params: params,
    headers: {
      accessToken: accessToken
    }
  });
};
export const deleteRequestBody = (url, params) => {
  let accessToken = getStore("accessToken");
  return service.delete(`${url}`, {
    // method: 'DELETE',
    // url: ,
    data: params,
    headers: {
      accessToken: accessToken
    }
  })
  // return service({
  //   method: 'DELETE',
  //   url: `${url}`,
  //   data: params,
  //   headers: {
  //     accessToken: accessToken
  //   }
  // });
};

export const importRequest = (url, params) => {
  let accessToken = getStore("accessToken");
  return service({
    method: "post",
    url: `${url}`,
    data: params,
    headers: {
      accessToken: accessToken
    }
  });
};

export const uploadFileRequest = (url, params) => {
  let accessToken = getStore("accessToken");
  return service({
    method: "post",
    url: `${url}`,
    data: params,
    headers: {
      accessToken: accessToken,
      'Content-Type': 'multipart/form-data'
    }
  });
};

/**
 * 无需token验证的请求 避免旧token过期导致请求失败
 * @param {*} url
 * @param {*} params
 */
export const getRequestWithNoToken = (url, params) => {
  return service({
    method: "get",
    url: `${url}`,
    params: params
  });
};

/**
 * 无需token验证的请求 避免旧token过期导致请求失败
 * @param {*} url
 * @param {*} params
 */
export const postRequestWithNoToken = (url, params) => {
  return service({
    method: "post",
    url: `${url}`,
    params: params
  });
};

/**
 * 无需token验证的请求 避免旧token过期导致请求失败
 * @param {*} url
 * @param {*} params
 */
export const postRequestWithNoTokenDataNew = (url, params) => {
  const headers = params.header || params.headers || {}
  delete params.header
  delete params.headers
  return service({
    method: "post",
    url: `${url}`,
    data: params,
    headers
  });
};

/**
 * 无需token验证的请求 避免旧token过期导致请求失败
 * @param {*} url
 * @param {*} params
 */
export const postRequestWithNoTokenData = (url, params) => {
  return service({
    method: "post",
    url: `${url}`,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: params
  });
};